﻿namespace Utility1
{
    using System;
    using System.Globalization;
    using System.IO;
    using System.Security.Cryptography;
    using System.Text;

    public class Encryption64
    {
        private static string ConvertBytesToHexString(byte[] data)
        {
            string str = "";
            foreach (byte num in data)
            {
                str = str + string.Format("{0:X2}", num);
            }
            return str;
        }

        private static byte[] ConvertHexStringToBytes(string hexString)
        {
            int num = hexString.Length / 2;
            byte[] buffer = new byte[num];
            for (int i = 0; i < num; i++)
            {
                buffer[i] = byte.Parse(hexString.Substring(i * 2, 2), NumberStyles.HexNumber);
            }
            return buffer;
        }

        public static string Decrypt(string stringToDecrypt, string sEncryptionKey)
        {
            byte[] rgbKey = new byte[0];
            byte[] rgbIV = new byte[] { 10, 20, 30, 40, 50, 60, 70, 80 };
            byte[] buffer = new byte[stringToDecrypt.Length];
            try
            {
                rgbKey = Encoding.GetEncoding("Shift-JIS").GetBytes(sEncryptionKey.Substring(0, 8));
                DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
                buffer = ConvertHexStringToBytes(stringToDecrypt);
                MemoryStream stream = new MemoryStream();
                CryptoStream stream2 = new CryptoStream(stream, provider.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                stream2.Write(buffer, 0, buffer.Length);
                stream2.FlushFinalBlock();
                return Encoding.GetEncoding("Shift-JIS").GetString(stream.ToArray());
            }
            catch
            {
                return "";
            }
        }

        public static string Encrypt(string stringToEncrypt, string sEncryptionKey)
        {
            byte[] rgbKey = new byte[0];
            byte[] rgbIV = new byte[] { 10, 20, 30, 40, 50, 60, 70, 80 };
            try
            {
                rgbKey = Encoding.GetEncoding("Shift-JIS").GetBytes(sEncryptionKey.Substring(0, 8));
                DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
                byte[] bytes = Encoding.GetEncoding("Shift-JIS").GetBytes(stringToEncrypt);
                MemoryStream stream = new MemoryStream();
                CryptoStream stream2 = new CryptoStream(stream, provider.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                stream2.Write(bytes, 0, bytes.Length);
                stream2.FlushFinalBlock();
                return ConvertBytesToHexString(stream.ToArray());
            }
            catch
            {
                return "";
            }
        }
    }
}

